package cn.fu.business;

import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class Test {

	public static void main(String[] args) {
		Filter f1=new Filter();
		f1.setId(1);//查询id为1的用户
		
		Filter f2=new Filter();
		f2.setUserName("99fu");//通过名字查询
		f2.setAge(30);
		
		Filter f3=new Filter();
		f3.setEmail("99fu@99fu.cn,admin@99fu.cn");//查询邮箱为其中任义的一个
		
		Filter2 f4=new Filter2();
		f4.setAmount(10);
		f4.setName("资源部");
		System.out.println(query(f4));
		
		String sql1=query(f1);
		String sql2=query(f2);
		String sql3=query(f3);		
		
		System.out.println(sql1);
		System.out.println(sql2);
		System.out.println(sql3);
	}
	private static String query(Object f){
		StringBuilder sb=new StringBuilder();
		//1.获取到class
		Class c=f.getClass();
		//获取taber的名字
		boolean exists = c.isAnnotationPresent(Table.class);
		//如果表名不存在直接返回
		if(!exists){
			return null;
		}
		//获取表名
		Table t = (Table)c.getAnnotation(Table.class);
		String tablerName= t.value();
		//得到表名生成sql
		sb.append("select * from ").append(tablerName).append(" where 1=1 ");
		
		//3.遍历所有的字段
		//3.1 得到所有的字段
		Field[] fields = c.getDeclaredFields();
		for (Field field : fields) {
			boolean FExists = field.isAnnotationPresent(Column.class);
			//3.2 如果不存在，说明是一个普通字段,跳过
			if(!FExists){
				continue;
			}
			
			//4. 处理每个字段对应的sql
			//4.1 拿到字段的名
			Column column = field.getAnnotation(Column.class);
			String columnName=column.value();
			
			//4.2 拿到字段的值
			// 4.2.1 拿到方法名
			String filedName=field.getName();
			
			//4.2.2 首字母大写(得到获取值的方法名)
			String getMethodName="get"+ filedName.substring(0, 1).toUpperCase()
					+filedName.substring(1);
			
			Object fieldValue=null;
			try {
				//4.2.3反射到方法
				Method declaredMethod = c.getDeclaredMethod(getMethodName);
				fieldValue = declaredMethod.invoke(f);
				
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			if(fieldValue == null || 
					(fieldValue instanceof Integer && (Integer)fieldValue==0)){
				continue;
			}
			//3.4拼装sql
			sb.append(" and ").append(filedName);
			if(fieldValue instanceof String){
				//3.5 处理in的拼接
				//3.5.1 如果包函,号的值
				if(((String) fieldValue).contains(",")){
					String[] split = ((String) fieldValue).split(",");
					sb.append(" in ").append(" ( ");
					for (String str : split) {
						sb.append("'").append(str).append("'").append(",");
					}
					sb.deleteCharAt(sb.length()-1);
					sb.append(")");
				}else{
				sb.append(" = ").append("'").append(fieldValue).append("'");
				}
			}else if(fieldValue instanceof Integer){
				sb.append(" = ").append(fieldValue);
			}
			
		}
		return sb.toString();
	}		
}
